package l1j.server.server.datatables;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.opqlo.NewSystem.NpcAction.ItemFusion;
import l1j.server.DatabaseFactory;
import l1j.server.server.templates.L1FusionTemp;
import l1j.server.server.utils.PerformanceTimer;
import l1j.server.server.utils.SQLUtil;

public class FusionTable {

	
	private final static Logger _log = Logger.getLogger(FusionTable.class.getName());
	
	private static FusionTable _instance;
	
	private final HashMap<Integer , ArrayList<L1FusionTemp>>_map = new HashMap<Integer , ArrayList<L1FusionTemp>>();
	private final HashMap<Integer , Integer>_countList = new HashMap<Integer , Integer>();
	
	public static FusionTable get(){
		if(_instance == null){
			_instance = new FusionTable();
			ItemFusion.load();
		}
		return _instance;
	}
	
	
	public void load(){
		
		
		final PerformanceTimer timer = new PerformanceTimer();
		Connection con = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		try {
			con = DatabaseFactory.get().getConnection();
			pstm = con.prepareStatement("SELECT * FROM `z_opqlo_合成清單`");
			rs = pstm.executeQuery();
			int size =0;
			while(rs.next()){
				final int srcitemid = rs.getInt("ItemId");
				final L1FusionTemp temp = new L1FusionTemp();
				if(temp.setItemId(rs.getInt("MaterialId"))){
					temp.setAmount(rs.getInt("MaterialCount"));
					final ArrayList<L1FusionTemp> list;
					if(_map.containsKey(srcitemid)){
						list = _map.get(srcitemid);
					}else{
						list = new ArrayList<L1FusionTemp>();
						_countList.put(srcitemid, rs.getInt("ItemCount"));
						_map.put(srcitemid, list);
					}
					size ++;
					list.add(temp);
				}
			}
			_log.info("載入物品合成資料數量: " + size + "(" + timer.get() + "ms)");			
			} catch (final SQLException e) {
				_log.log(Level.WARNING,e.getLocalizedMessage(), e);
			} finally {
				SQLUtil.close(rs);
				SQLUtil.close(pstm);
				SQLUtil.close(con);
			}
	}
	
	public int getCount(final int itemid){
		if(_countList.containsKey(itemid)){
			return _countList.get(itemid);
		}
		return 0;
	}
	
	public ArrayList<L1FusionTemp>getList(final int itemid){
		return _map.get(itemid);
	}
	
	
	
}
